package com.ourhours.message.configuration;//package com.ourhours.push.configuration;

import com.ourhours.message.common.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Description:WebAdvice.
 *
 * @author xiangyang.liu
 * @version V1.0
 * @since 2017/9/15
 */
@ControllerAdvice
@Slf4j
public class WebAdvice {

    @ExceptionHandler
    public String handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        log.error("error:", e);
        if (isAjax(request)) {
            BaseResult<Object> result = BaseResult.failure(e.getMessage());
            //ajaxResult(response, JSON.toJSONString(result));
            return null;
        }
        return "error";
    }

    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }

    public static void ajaxResult(HttpServletResponse response, String res) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(res);
            out.flush();
        } catch (IOException var4) {
            log.error(var4.toString());
        }
    }

}
